package com.lihao.wanandroid.ui.tree

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.tabs.TabLayout
import com.kingja.loadsir.core.LoadService
import com.lihao.jetpackcore.ext.getViewModel
import com.lihao.jetpackcore.ext.nav
import com.lihao.jetpackcore.ext.parseState
import com.lihao.jetpackcore.ext.util.dp2px
import com.lihao.jetpackcore.util.LogUtils
import com.lihao.jetpackcore.util.ToastUtil
import com.lihao.wanandroid.R
import com.lihao.wanandroid.app.base.BaseFragment
import com.lihao.wanandroid.app.ext.*
import com.lihao.wanandroid.app.util.VibrateUtils
import com.lihao.wanandroid.app.weight.recyclerview.SpaceItemDecoration
import com.lihao.wanandroid.data.model.CollectEvent
import com.lihao.wanandroid.data.model.TreeResponse
import com.lihao.wanandroid.ui.collect.CollectViewModel
import com.lihao.wanandroid.ui.home.recommend.ArticleAdapter
import kotlinx.android.synthetic.main.fragment_tree.*
import me.hgj.jetpackmvvm.demo.app.weight.loadCallBack.LoadingCallback

/**
 * Created by lihao on 2020/5/19.
 * Describe: 知识体系Fragment
 */
class TreeFragment : BaseFragment<TreeViewModel>() {

    //界面状态管理者
    private lateinit var loadsir: LoadService<Any>

    private val collectViewModel: CollectViewModel by lazy {
        getViewModel<CollectViewModel>()
    }

    private val titleAdapter: TreeReclassifyAdapter by lazy {
        TreeReclassifyAdapter().apply {
            setOnItemClickListener { adapter, view, position ->
                if (position != selectItemPosition) {
                    loadsir.showLoading()
                    selectItem(position)
                    mViewModel.getArticleData(cid = titleAdapter.data[position].id)
                }
            }
        }
    }

    private val articleAdapter: ArticleAdapter by lazy {
        ArticleAdapter().apply {
            setAdapterAnimation(2)
            loadMoreModule.setOnLoadMoreListener {
                mViewModel.getArticleData(mViewModel.pageNo, mViewModel.cid)
            }
            setOnItemClickListener { adapter, view, position ->
                val bundle = Bundle()
                bundle.putParcelable("articleData", data[position])
                nav().navigate(R.id.action_to_webFragment, bundle)
            }
            setOnItemChildClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.tvCollect -> {
                        VibrateUtils.vibrate(40)
                        if (shareViewModel.isLogin.value) {
                            if (articleAdapter.data[position].collect) {
                                collectViewModel.uncollectArticle(articleAdapter.data[position].id)
                            } else {
                                collectViewModel.collectArticleIn(articleAdapter.data[position].id)
                            }
                        } else {
                            nav().navigate(R.id.action_to_loginFragment)
                        }
                    }
                }
            }
        }
    }

    override fun layoutId(): Int = R.layout.fragment_tree

    override fun initView(savedInstanceState: Bundle?) {
        loadsir = LoadServiceInit(recyclerArticle) {
            loadsir.showCallback(LoadingCallback::class.java)
            mViewModel.getTree()
        }
        initTitle("知识体系", isShowBack = false)

        // tabLayout点击事件
        if (mViewModel.treeList.size > 0) {
            for (item in mViewModel.treeList) {
                tabLayout.addTab(tabLayout.newTab().setText(item.name))
            }
        }
        tabLayout.getTabAt(mViewModel.curTabIndex)?.select()
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.run {
                    loadsir.showLoading()
                    mViewModel.curTabIndex = tab.position
                    titleAdapter.setList(mViewModel.treeList[tab.position].children)
                    mViewModel.getArticleData(cid = titleAdapter.data[titleAdapter.selectItemPosition].id)
                }
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }
        })
        // 二级分类
        recyclerTitle.init(
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false),
            titleAdapter
        ).run {
            addItemDecoration(SpaceItemDecoration(dp2px(8), dp2px(8)))
        }
        // 文章列表
        recyclerArticle.init(LinearLayoutManager(context), articleAdapter).run {
            addItemDecoration(SpaceItemDecoration(0, dp2px(8)))
        }
        // 刷新事件
        swipeRefresh.setOnRefreshListener {
            mViewModel.getArticleData(cid = mViewModel.cid)
        }
    }

    override fun lazyLoadData() {
        loadsir.showLoading()
        mViewModel.getTree()
    }

    override fun createObserver() {
        mViewModel.treeData.observe(this, Observer { resultState ->
            parseState(resultState, {
                if (it.size > 0) {
                    mViewModel.treeList.clear()
                    it[0].isChecked = true
                    for (item in it) {
                        if (item.children.size > 0) {
                            item.children[0].isChecked = true
                        }
                        mViewModel.treeList.add(item)
                        tabLayout.addTab(tabLayout.newTab().setText(item.name))
                    }
                } else {
                    swipeRefresh.isRefreshing = false
                    loadsir.showEmpty()
                }
            }, {
                ToastUtil.showShort(context, it.errorMsg)
                swipeRefresh.isRefreshing = false
                loadsir.showError(it.errorMsg)
            })
        })

        mViewModel.articleData.observe(this, Observer { resultState ->
            parseState(resultState, {
                mViewModel.pageNo++
                when {
                    it.isFirstEmpty() -> {
                        swipeRefresh.isRefreshing = false
                        loadsir.showEmpty()
                    }
                    it.isRefresh() -> {
                        swipeRefresh.isRefreshing = false
                        loadsir.showSuccess()
                        articleAdapter.setList(it.datas)
                    }
                    else -> {
                        loadsir.showSuccess()
                        articleAdapter.addData(it.datas)
                        if (it.hasMore()) {
                            articleAdapter.loadMoreModule.loadMoreComplete()
                        } else {
                            articleAdapter.loadMoreModule.loadMoreEnd()
                        }
                    }
                }

            }, {
                ToastUtil.showShort(context, it.errorMsg)
                if (mViewModel.pageNo.isRefresh()) {
                    swipeRefresh.isRefreshing = false
                    loadsir.showError(it.errorMsg)
                } else {
                    articleAdapter.loadMoreModule.loadMoreFail()
                }
            })

        })

        // 收藏结果
        collectViewModel.collectState.observe(this, Observer {
            if (it.isSuccess) {
                ToastUtil.showShort(context, if (it.collect) "收藏成功！" else "取消收藏！")
                eventViewModel.collect.value = CollectEvent(it.id, it.collect)
            } else {
                ToastUtil.showShort(context, it.errorMsg)
            }
        })

        // 登陆状态
        shareViewModel.run {
            userInfo.observe(viewLifecycleOwner, Observer {
                if (it != null) {
                    it.collectIds.forEach { id ->
                        for (item in articleAdapter.data) {
                            if (id.toInt() == item.id) {
                                item.collect = true
                                break
                            }
                        }
                    }
                } else {
                    for (item in articleAdapter.data) {
                        item.collect = false
                    }
                    articleAdapter.notifyDataSetChanged()
                }
            })
        }
        eventViewModel.collect.observe(this, Observer {
            for (index in articleAdapter.data.indices) {
                if (articleAdapter.data[index].id == it.id) {
                    articleAdapter.data[index].collect = it.collect
                    articleAdapter.notifyDataSetChanged()
                    break
                }
            }
        })
    }

}